<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ this.$router.currentRoute.name }}</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 系统通知列表卡片区 -->
    <el-card class="box-card">
      <el-page-header style="margin-bottom: 2vh" @back="goBack"
                      :content="this.$router.currentRoute.name.substring(this.$router.currentRoute.name.indexOf('/')+1)">
      </el-page-header>
      <el-form :inline="true" ref="form" :model="queryMap" label-width="120px" size="small">
        <el-row>
          <h4 style="margin: 1vh 0 2vh;color: #1f2d3d">条件查询区</h4>
        </el-row>
        <el-form-item>
          <el-input
              @keyup.enter.native="searchSysNotice"
              @clear="searchSysNotice"
              clearable
              v-model="queryMap.title"
              placeholder="请输入系统通知标题"
          ></el-input>
        </el-form-item>

        <el-form-item style="margin-left:1vh">
          <el-button type="primary" @click="searchSysNotice" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-form>
      <div style="margin-bottom: 10px;display: flex">
        <span class="hint" style="flex: 1;"></span>
        <el-button
            icon="el-icon-plus"
            @click="addDialogVisible=true"
            v-hasPermission="'sysnotice:add'"
        >添加
        </el-button>
        <el-button @click="delMore">多选删除</el-button>
        <!--              <el-button @click="downExcel" v-hasPermission="'sysnotice:export'"  icon="el-icon-download">导出</el-button>-->
      </div>

      <!-- 表格区域 -->
      <el-table ref="multipleTable" v-loading="loading" size="small" :data="sysNoticeList"
                @selection-change="handleSelectionChange"
                border style="width: 100%;" height="420">
        <el-table-column type="selection" width="40"></el-table-column>
        <!--
            <el-table-column prop="noticeId" label="ID" width="50"></el-table-column>
        --> <!-- 已注释掉此行 -->
        <!--                <input type="hidden" v-model="form.hiddenField" />-->
        <el-table-column prop="title" label="标题" width="100"></el-table-column>
        <el-table-column label="通知内容" prop="noticeContent" width="200">
        </el-table-column>
        <el-table-column prop="level" label="等级" width="80">
          <template v-slot="scope">
            <span>{{ showLevel(scope.row) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="isRead" label="是否已读" width="80">
          <template v-slot="scope">
            <span>{{ showIsRead(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160"></el-table-column>
        <el-table-column prop="isPublish" label="是否发布" width="80">
          <template v-slot="scope">
            <span>{{ showIsPublish(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="创建人" width="100"></el-table-column>
        <el-table-column label="备注" prop="remark" width="200">
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-tooltip content="编辑" placement="top" effect="light">
              <el-button circle round plain size="small" type="primary" icon="el-icon-edit-outline"
                         @click="edit(scope.row.noticeId)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" effect="light">
              <el-button circle round plain type="danger" size="small" icon="el-icon-delete"
                         @click="del(scope.row.noticeId)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>

      </el-table>

      <!-- 分页 -->
      <el-pagination
          style="margin-top:10px;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryMap.pageNo"
          :page-sizes="[6, 10, 20, 30]"
          :page-size="queryMap.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>

      <!-- 添加对话框 -->
      <el-dialog :title="title" @close="closeDialog" :visible.sync="addDialogVisible" width="50%;">
        <!-- 表单 -->
        <span>
          <el-form
              :model="addForm"
              :label-position="labelPosition"
              :rules="addFormRules"
              ref="addFormRef"
              label-width="80px"
          >


            <el-row>
            <el-col :span="11">
               <div class="grid-content bg-purple">
                 <el-form-item label="标题" prop="title">
                  <el-input v-model="addForm.title"></el-input>
                </el-form-item>
              </div>
              </el-col>
            </el-row>

             <el-row>
               <div class="grid-content bg-purple">
                  <el-form-item label="内容" prop="noticeContent">
                    <el-input
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 8}"
                        placeholder="请输入内容"
                        v-model="addForm.noticeContent">
                  </el-input>
                  </el-form-item>
                </div>
             </el-row>

            <el-row>
            <el-col :span="11">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="等级" prop="level">
                    <el-radio-group v-model="addForm.level">
                      <el-radio :label="1" :value="1">普通</el-radio>
                      <el-radio :label="2" :value="2">紧级</el-radio>
                      <el-radio :label="3" :value="3">重要</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-col>
               </el-row>
            <el-row>
              <el-col :span="11">
               <div class="grid-content bg-purple-light">
                  <el-form-item label="是否发布" prop="isPublish">
                    <el-radio-group v-model="addForm.isPublish">
                      <el-radio :label="0" :value="0">不发布</el-radio>
                      <el-radio :label="1" :value="1">发布</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>


            <el-row>
                <el-form-item label="备注">
                  <el-input
                      type="textarea"
                      :autosize="{ minRows: 4, maxRows: 8}"
                      v-model="addForm.remark">
                  </el-input>
                </el-form-item>
            </el-row>
            <el-row>
              <el-col :span="11">
               <div class="grid-content bg-purple-light">
                  <el-form-item label="发布范围" prop="isPublish">
                    <el-radio-group v-model="addForm.isScope">
                      <el-radio :label="0" :value="0">内部</el-radio>
                      <el-radio :label="1" :value="1">全部</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </span>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button
              type="primary"
              @click="addSysNotice"
              :loading="btnLoading"
              :disabled="btnDisabled"
          >确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
  </div>
</template>
<script>
import axios from "axios";

export default {
  data() {
    return {
      title: '添加系统通知',
      btnLoading: false,
      btnDisabled: false,
      sysnotices: [],
      loading: true,
      total: 0,
      addDialogVisible: false, //添加对话框,
      editDialogVisible: false, //修改对话框
      assignDialogVisible: false, //分配角色对话框
      labelPosition: "right", //lable对齐方式
      multipleSelection: [],
      //查询对象
      queryMap: {
        pageNum: 1,
        pageSize: 6,
        title: "",
      },
      sysNoticeList: [],
      addForm: {
        title: '',
        noticeContent: '',
        level: 1,
        isPublish: 0,
        remark: '',
        isScope:0,
      },
      addFormRules: {
        title: [
          {required: true, message: "请输入标题", trigger: "blur"},
        ],
      }
    };
  },
  methods: {
    /**
     * 重置
     */
    reset() {
      this.queryMap = {
        pageNum: 1,
        pageSize: 6,
        title: "",
        noticeContent: ""
      };
    },
    //内容居中
    rowStyle() {
      return "text-align:center";
    },

    /**
     * 全选功能
     *
     */

    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    //多选删除
    async delMore() {
      const ids = this.multipleSelection.map(row => row.noticeId); // 提取出所有选中行的ID
      if (ids.length>0) {
        const res = await this.$confirm(
            "此操作将永久删除该系统通知, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
        ).catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
        if (res === "confirm") {
          const {data: res} = await this.$http.post("/system/sysnotice/delmore/", {ids});
          //const response = await axios.post('/api/delete', { ids }); // 发送删除请求
          console.log(res);
          if (res.success) {
            this.$notify.success({
              title: '操作成功',
              message: '系统通知删除成功',
            });
            await this.getSysNoticeList();
          } else {
            this.$message.error(res.data.errorMsg);
          }
        }
      }else {
        this.$message({
          title:'操作失败',
          message:"未选中系统通知",
        });
      }
    },

    /**
     * 加载系统通知表格
     */
    downExcel() {
      const $this = this;
      const res = axios
          .request({
            url: "http://47.99.186.44:8990/system/sysnotice/excel",
            method: "post",
            responseType: "blob",
            headers: {'Authorization': LocalStorage.get(LOCAL_KEY_XINGUAN_ACCESS_TOKEN)},	//设置请求头
          })
          .then(res => {
            if (res.headers["content-type"] === "application/json") {
              return $this.$message.error(
                  "Subject does not have permission [class:export]"
              );
            }
            const data = res.data;
            let url = window.URL.createObjectURL(data); // 将二进制文件转化为可访问的url
            const a = document.createElement("a");
            document.body.appendChild(a);
            a.href = url;
            a.download = "系统通知列表.xls";
            a.click();
            window.URL.revokeObjectURL(url);
          });
    },


    /**
     * 加载系统通知列表
     */
    async getSysNoticeList() {
      const {data: res} = await this.$http.get("/system/sysnotice/findList", {
        params: this.queryMap
      });
      if (!res.success) {
        return this.$message.error("获取系统通知列表失败:" + res.data.errorMsg);
      }
      this.total = res.data.total;
      this.sysNoticeList = res.data.rows;
      this.loading = false;
    },

    /**
     * 删除通知
     */
    async del(id) {
      const res = await this.$confirm(
          "此操作将永久删除该系统通知, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
      if (res === "confirm") {
        const {data: res} = await this.$http.delete("/system/sysnotice/delete/" + id);
        console.log(res);
        if (res.success) {
          this.$notify.success({
            title: '操作成功',
            message: '系统通知删除成功',
          });
          await this.getSysNoticeList();
        } else {
          this.$message.error(res.data.errorMsg);
        }
      }
    },
    /**
     * 添加系统通知
     */
    async addSysNotice() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return;
        } else {
          if (this.addForm.noticeId) {
            this.updateSysNotice()
          } else {
            this.saveSysNotice()
          }
        }
      });
    },
    async saveSysNotice() {
      this.btnLoading = true;
      this.btnDisabled = true;
      const {data: res} = await this.$http.post("/system/sysnotice/add", this.addForm);
      if (res.success) {
        this.$notify.success({
          title: '操作成功',
          message: '系统通知添加成功',
        });
        this.addForm = {};
        await this.getSysNoticeList();
      } else {
        return this.$message.error("系统通知添加失败:" + res.data.errorMsg);
      }
      this.addDialogVisible = false;
      this.btnLoading = false;
      this.btnDisabled = false;
    },
    /**
     * 更新系统通知
     */
    async updateSysNotice() {
      this.btnLoading = true;
      this.btnDisabled = true;
      const {data: res} = await this.$http.put(
          "/system/sysnotice/update/" + this.addForm.noticeId,
          this.addForm
      );
      if (res.success) {
        this.$notify({
          title: "操作成功",
          message: "系统通知的基本信息已更新",
          type: "success"
        });
        this.addForm = {};
        await this.getSysNoticeList();
      } else {
        this.$message.error("系统通知信息更新失败:" + res.data.errorMsg);
      }
      this.addDialogVisible = false;
      this.btnLoading = false;
      this.btnDisabled = false;
    },
    /**
     * 搜索系统通知
     */
    searchSysNotice() {
      this.queryMap.pageNum = 1;
      this.getSysNoticeList();
    },
    /**
     * 修改系统通知
     */
    async edit(id) {
      this.title = "编辑系统通知信息"
      const {data: res} = await this.$http.get("/system/sysnotice/edit/" + id);
      if (res.success) {
        this.addForm = res.data;
        this.addDialogVisible = true;
      } else {
        return this.$message.error("系统通知信息编辑失败:" + res.data.errorMsg);
      }
    },
    /**
     *  改变页码
     */
    handleSizeChange(newSize) {
      this.queryMap.pageSize = newSize;
      this.getSysNoticeList();
    },
    /**
     * 翻页
     */
    handleCurrentChange(current) {
      this.queryMap.pageNum = current;
      this.getSysNoticeList();
    },

    /**
     * 关闭添加弹出框
     */
    closeDialog() {
      this.$refs.addFormRef.clearValidate();
      this.addForm.birth = "";
      this.addForm = {};
    },
    /**
     * 关闭编辑弹出框
     */
    editClose() {
      this.$refs.editFormRef.clearValidate();
      this.editForm = {};
    },
    /**
     * 显示等级
     */
    showLevel(row, column) {
      let level = '';
      if (row.level == 1) {
        level = '普通';
      } else if (row.level == 2) {
        level = '紧急';
      } else if (row.level == 3) {
        level = '重要';
      } else {
        level = '普通';
      }
      return level;
    },
    /**
     * 是否已读
     */
    showIsRead(row, column) {
      let read = '';
      if (row.isRead == 0) {
        read = '未读';
      } else if (row.isRead == 1) {
        read = '已读';
      } else {
        read = '未读';
      }
      return read;
    },

    /**
     * 是否发布
     */
    showIsPublish(row, column) {
      let isPublish = '';
      if (row.isPublish == 0) {
        isPublish = '不发布';
      } else if (row.isPublish == 1) {
        isPublish = '发布';
      } else {
        isPublish = '不发布';
      }
      return isPublish;
    },

  },
  created() {
    this.getSysNoticeList();
    // setTimeout(() => {
    //     this.loading = false;
    // }, 500);
  }
};
</script>
